package com.wondersgroup.framework.sample.component.demoform.action;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.wondersgroup.framework.core.web.struts2.action.BaseAjaxAction;
import com.wondersgroup.framework.core5.model.vo.ValueObject;
import com.wondersgroup.framework.sample.component.demoform.vo.UploadVO;
import com.wondersgroup.framework.sample.component.demoform.vs.DemoVS;

public class UploadAction extends BaseAjaxAction {

	private DemoVS demoVS;
	private UploadVO uploadVO = new UploadVO();

	public DemoVS getDemoVS() {
		return demoVS;
	}

	public void setDemoVS(DemoVS demoVS) {
		this.demoVS = demoVS;
	}

	public UploadVO getUploadVO() {
		return uploadVO;
	}

	public void setUploadVO(UploadVO uploadVO) {
		this.uploadVO = uploadVO;
	}

	@Override
	public ValueObject getValueObject() {
		return this.uploadVO;
	}

	@Override
	public String operate() {
		String result = prefix + suffex;
		return result;
	}

	public void writerJson(String json) {
		HttpServletResponse response = ServletActionContext.getResponse();
		String contentType = "text/html" + ";charset=" + "UTF-8";
		response.setContentType(contentType);
		try {
			response.getWriter().write(json);
			response.getWriter().flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String doUpload() {
		String realPath = ServletActionContext.getServletContext().getRealPath("");
		String json = "";
		if (this.uploadVO.getFileData() == null) {
			json = prefix + "{\"flag\":" + "\"0\",\"msg\":" + "\"请上传附件！\"" + "}" + suffex;
		} else {
			for (int i = this.uploadVO.getFileData().length - 1; i >= 0; --i) {
				File destFile = new File(realPath + "\\destFile\\" + this.uploadVO.getFileDataFileName()[i]);
				try {
					FileUtils.copyFile(this.uploadVO.getFileData()[i], destFile);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			this.demoVS.doImport(uploadVO);
			json = prefix + "{\"flag\":" + "\"1\",\"msg\":" + "\"附件上传成功！\"" + "}" + suffex;
		}
		this.writerJson(json);
		return AJAX;
	}
}
